package com.yirui.serialcomm.server;

import com.fazecast.jSerialComm.SerialPort;
import com.yirui.serialcomm.core.protocol.Context;
import com.yirui.serialcomm.service.Connection;
import com.yirui.serialcomm.service.ConnectionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 串口到网络桥接通信服务
 * @author Dujie
 * @create 2025/8/13
 * @since 1.0.0
 */
@Component
@Slf4j
public class SerialCommToNetwork {
    private ConnectionManager manager;
    private Map status = new HashMap();
    @Scheduled(fixedRateString = "${connect.check.interval:30000}")
    private void checkConnect(){
        if(manager != null){
            manager.start();
        }
    }
    public void start(Context ctx) {
        manager = new ConnectionManager(ctx);
        Map net = new HashMap();
        net.put("targetIp", ctx.getTargetIp());
        net.put("tcp", ctx.getTcpPort());
        net.put("udp", ctx.getUdpPort());
        status.put("bridge-net", net);
        SerialPort[] ports = SerialPort.getCommPorts();
        log.info("###############################################");
        log.info("序号 |  名称   |   描述   |   位置");
        int i = 1;
        List portList = new ArrayList<>();
        for (SerialPort port : ports) {
            log.info("  {} | {} | {} | {}",i++, port.getSystemPortName(), port.getDescriptivePortName(),port.getPortLocation());
            manager.addConnection(port);
            portList.add(port.getSystemPortName());
        }
        status.put("bridge-comm-list", portList);
        manager.start();
    }

    @PreDestroy
    public void stop(){
        manager.destroy();
    }

    public Map getStatus() {
        return status;
    }
}
